package test.myorm;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.ImmutableMap;

import test.myorm.App2.User;
import test.myorm.core.ResultMap;
import test.myorm.core.Sql;
import test.myorm.handler.ResultSetHandler;
import test.myorm.handler.StatementHandler;

/**
 * Hello world!
 *
 */
public class App {
	public static void main(String[] args) throws SQLException {
		String url = "jdbc:mysql://10.167.202.83:3306/mytest?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false";
		String username = "root";
		String password = "root";
		DataSource dataSource = getDataSource(url, username, password);
		Connection conn = dataSource.getConnection();
		
		Sql sql = getSql();
		String sqlStr = sql.getSql();
		List<Object> params = sql.getParameter().getParamList();
		
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		StatementHandler stHandler = new StatementHandler();
		Statement stat = stHandler.handle(sql, conn);
		
		
		if(sql.getType()==1) {
			rs = ps.executeQuery();
			ResultSetHandler rsHandler = new ResultSetHandler();
			Object obj = rsHandler.handle(sql, rs);
			List list = rsHandler.list(obj);
			System.out.println(list);
		} else {
			ps.execute(sqlStr);
		}
	}
	
	static DataSource getDataSource(String url, String username, String password) {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		return dataSource;
	}
	
	static Sql getSql() {
		Sql sql = new Sql();
		sql.setType(Sql.SQL_SELECT);
//		sql.setSql("select * from user where id = ?");
		sql.setSql("select * from user where age = ?");
//		sql.setParams(Arrays.asList(10));
		ResultMap resultMap = new ResultMap();
		resultMap.setClazz(User.class);
		resultMap.setColumnMapping(ImmutableMap.of("age", "javaPropertyAge"));
//		resultMap.setColumnMapping(new HashMap());
		sql.setResultMap(resultMap);
		return sql;
	}
	
}
